import path from "path";
import {
  getDist,
  getPathAndFileName2Config,
} from "./getPathAndFileName2Config";
import { showErrorMessage, showInformationMessage } from "./message";
import { spawnSync } from "child_process";
import * as vscode from "vscode";
import getFilePath from "./getFilePath";
import { updatePackageJson } from "../packageJson";

export async function selectNPMPackagePath() {
  const cwd = getFilePath() || process.cwd();
  interface ExtendedQuickPickItem extends vscode.QuickPickItem {
    dts?: string;
    file: string[];
    type: "server" | "client" | undefined;
  }
  let pathItems: ExtendedQuickPickItem[] = [];

  function createPathItem(
    label: string,
    base: string,
    configPath: string,
    distPath: string,
  ): ExtendedQuickPickItem {
    const jsPath = path
      .relative(
        cwd,
        path.posix.normalize(
          path.resolve(distPath, replaceExtension(configPath, "js")),
        ),
      )
      .replace(/\\/g, "/");
    const dtsPath = path
      .relative(
        cwd,
        path.resolve(distPath, replaceExtension(configPath, "d.ts")),
      )
      .replace(/\\/g, "/");
    const filePath = path
      .relative(cwd, path.resolve(distPath, path.dirname(configPath)))
      .replace(/\\/g, "/");
    const type = label === "切换至服务端包" ? "server" : "client";
    return {
      label,
      detail: jsPath,
      dts: dtsPath,
      type,
      file: [filePath + "/**/*"],
    };
  }

  const pathAndFileName2Config = await getPathAndFileName2Config();
  if (pathAndFileName2Config) {
    let distPath = await getDist(pathAndFileName2Config.server.base);
    pathItems.push(
      createPathItem(
        "切换至服务端包",
        pathAndFileName2Config.server.base,
        pathAndFileName2Config.server.path,
        distPath,
      ),
    );

    let distPath2 = await getDist(pathAndFileName2Config.client.base);
    pathItems.push(
      createPathItem(
        "切换至客户端包",
        pathAndFileName2Config.client.base,
        pathAndFileName2Config.client.path,
        distPath2,
      ),
    );

    pathItems.push({
      label: "切换至地图项目",
      type: undefined,
      file: [],
    });
  }

  const selectedOption = await vscode.window.showQuickPick(pathItems, {
    title: "配置神岛组件库（npm包）用途",
    matchOnDescription: true,
    canPickMany: false,
  });

  if (selectedOption) {
    const soawnObj = {
      stdio: "ignore",
      shell: true,
      cwd,
    };
    let pkgSetCmd = "npm";
    let pkgSetArgs = ["pkg", "set"];
    pkgSetArgs.push("files[0]=" + selectedOption.file[0]);
    pkgSetArgs.push("main=" + selectedOption.detail);
    pkgSetArgs.push("types=" + selectedOption.dts);
    // @ts-ignore
    const pkgSet = spawnSync(pkgSetCmd, pkgSetArgs, soawnObj);
    if (pkgSet.error) {
      console.error(pkgSet.error);
      process.exit(1);
    }

    if (pkgSet.status !== 0) {
      console.error("修改失败 package.json");
      process.exit(1);
    }
    await updatePackageJson("npmPackage", selectedOption.type);

    showInformationMessage("修改package.json成功，已" + selectedOption.label);
  }
}

function replaceExtension(filename: string, newExtension: string): string {
  const baseName = filename.slice(0, filename.lastIndexOf("."));
  return `${baseName}.${newExtension}`;
}
